//
//  SettingViewController.m
//  Stock
//
//  Created by blacksun on 11-7-9.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "SettingViewController.h"
#import "CommonUtil.h"
#import "MobClick.h"
#import "FeedbackViewController.h"
#import "ChargeSyncController.h"
#import "StockAppHelper.h"


@implementation SettingViewController
@synthesize tableView;
@synthesize cellTitles;
@synthesize appService;



- (void)dealloc
{
    self.tableView = nil;
    self.cellTitles = nil;
    self.appService = nil;
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"设置";
    self.appService = [[[StockAppService alloc] initWithDelegate:self] autorelease];
    [self.navigationController setNavigationBarHidden:NO];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    NSArray *title1 = [NSArray arrayWithObjects:@"建议反馈",@"免责声明",@"给软件评分",IsPaidVersion?nil:@"升级到专业版",nil];
    //NSArray *title2 = [NSArray arrayWithObjects:@"",/*@"QQ群",*/nil];
    self.cellTitles = [NSArray arrayWithObjects:[NSArray arrayWithObject:@"登录/注册"],[NSArray arrayWithObjects:@"所有股票",@"自选股",nil],title1, nil];
    
    /*UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = doneButton;
    [doneButton release];*/
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}
-(void)close{
    [self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    self.tableView = nil;
    self.cellTitles = nil;
    self.appService = nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[cellTitles objectAtIndex:section] count];
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"SettingViewCell";
    
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 12.0, 80.0, 20.0)];
        leftLabel.tag = 999;
        leftLabel.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:leftLabel];
        [leftLabel release];
        
        /*UILabel *rightLabel = [[UILabel alloc] initWithFrame:CGRectMake(80.0, 12.0, 210.0, 20.0)];
        rightLabel.tag = 10000;
        rightLabel.backgroundColor = [UIColor clearColor];
        rightLabel.textColor = [UIColor blackColor];
        rightLabel.textAlignment = UITextAlignmentRight;
        [cell.contentView addSubview:rightLabel];
        [rightLabel release];
        */
        
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    UILabel *leftLabel = (UILabel *)[cell viewWithTag:999];
    if (indexPath.section==1) {
        NSUserDefaults *userDefualt = [NSUserDefaults standardUserDefaults];
        NSInteger range = [userDefualt integerForKey:RadarRangeKey];
        if (range==0) {
            range=2;
            [userDefualt setInteger:range forKey:RadarRangeKey];
            [userDefualt synchronize];
        }
        if ((indexPath.row==0 && range==2) || (indexPath.row==1 && range==1)) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        
    }else {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    
    NSString *chargeEmail = [[StockContext shareInstance] savedChargeEmail];
    if (indexPath.section==0 && chargeEmail.length !=0) {
        leftLabel.text = chargeEmail;
    }else {
        leftLabel.text = [[cellTitles objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    }
    
    [leftLabel sizeToFit];
    return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    NSString *title = nil;
    switch (section) {
        case 0:
            title = @"同步购买";
            break;
        case 1:
            title = @"雷达探测范围";
            break;
        case 2:
            title = @"关于";
            break;
        default:
            break;
    }
    return title;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
        ChargeSyncController *controller = [[ChargeSyncController alloc] initWithNibName:@"ChargeSyncController" bundle:nil];
        [self.navigationController pushViewController:controller animated:YES];
        [controller release];
    }else if (indexPath.section==1) {
        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        NSInteger range = [userDefault integerForKey:RadarRangeKey];
        if ((indexPath.row==0&&range!=2) || (indexPath.row==1&&range!=1)) {
            [appService modifyRadarRange:range==2 ? 1 : 2];
        }
    }else if(indexPath.section==2){
        if (indexPath.row==0) {
            FeedbackViewController *feedBackController = [[FeedbackViewController alloc] initWithNibName:@"FeedbackViewController" bundle:nil];
            [self.navigationController pushViewController:feedBackController animated:YES];
            [feedBackController release];
        }else if (indexPath.row==1) {
            SettingWebviewController *webViewController = [[SettingWebviewController alloc] initWithNibName:@"SettingWebviewController" bundle:nil];
            NSString *htmlString= [NSString stringWithContentsOfFile:[[CommonUtil shareInstance] pathOfResouceInMainBundle:@"about.html"] encoding:NSUTF8StringEncoding error:nil];
            webViewController.htmlString = htmlString;
            
            webViewController.title = [[self.cellTitles objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
            [self.navigationController pushViewController:webViewController animated:YES];
            [webViewController release];
        }else{
            NSString *appStoreURL = nil;
            if (indexPath.row==2) {
                appStoreURL = AppStoreLink;
            }else{
                appStoreURL = ProVersionAppStoreLink;
            }
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:appStoreURL]];
        }
    }
}

#pragma mark ServiceDelegate;
-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    if ([action isEqualToString:kStockAppServiceModifyRadarRange]) {
        if ([[aResult objectForKey:@"success"] boolValue]) {
            NSInteger range = [[aUserinfo objectForKey:@"range"] intValue];
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setInteger:range forKey:RadarRangeKey];
            [userDefault synchronize];
            [self.tableView reloadData];
        }else {
            [[StockAppHelper shareInstance] showAlertViewWithMessage:@"网络错误。"];
        }
        
    }
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    [[StockAppHelper shareInstance] showAlertViewWithMessage:aError.domain];
}
@end
